package com.autotest.nore.controller;

import com.autotest.nore.common.exception.TokenEmptyException;
import com.autotest.nore.common.utils.PageUtils;
import com.autotest.nore.common.utils.Pager;
import com.autotest.nore.dto.ApiDTO;
import com.autotest.nore.request.ApiRequest;
import com.autotest.nore.request.QueryRequest;
import com.autotest.nore.service.ApiService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;


@RestController
@RequestMapping("/autotest/api")
public class ApiController {

    @Autowired
    private ApiService apiService;

    @PostMapping("/save")
    public void saveApi(@RequestBody ApiRequest apiRequest, HttpServletRequest request) {
        HttpSession session = request.getSession(false); // 获取会话，如果不存在则返回null
        if (session == null || session.getAttribute("userName") == null) {
            throw new TokenEmptyException("用户未登录，请重新登录");
        }
        String userName = session.getAttribute("userName").toString();
        apiRequest.setUpdateUser(userName);
        apiService.saveApi(apiRequest);
    }

    @PostMapping("/copy")
    public void copyApi(@RequestBody ApiRequest apiRequest, HttpServletRequest request) {
        HttpSession session = request.getSession(false); // 获取会话，如果不存在则返回null
        if (session == null || session.getAttribute("userName") == null) {
            throw new TokenEmptyException("用户未登录，请重新登录");
        }
        String userName = session.getAttribute("userName").toString();
        apiRequest.setUpdateUser(userName);
        apiService.copyApi(apiRequest);
    }



    @PostMapping("/delete")
    public void deleteApi(@RequestBody ApiRequest request) {
        apiService.deleteApi(request);
    }

    @GetMapping("/detail/{apiId}")
    public ApiDTO getApiDetail(@PathVariable String apiId){
        return apiService.getApiDetail(apiId);
    }

    @PostMapping("/list/{goPage}/{pageSize}")
    public Pager<List<ApiDTO>> getApiList(@PathVariable int goPage, @PathVariable int pageSize,
                                          @RequestBody QueryRequest request) {
        Page<Object> page = PageHelper.startPage(goPage, pageSize, true);
        return PageUtils.setPageInfo(page, apiService.getApiList(request));
    }








}
